
package hasthi.metamodel;

import static hasthi.common.constants.HasthiConstants.GET_COORDINATOR_STATE_ACTION;
import hasthi.common.BaseContext;
import hasthi.common.HasthiException;
import hasthi.common.HasthiException.FaultCode;
import hasthi.container.MessageContext;
import hasthi.container.SimpleMessageContext;
import hasthi.container.UnicastContianier;
import hasthi.manager.CoordinatorStateRequestDocument;
import hasthi.manager.CoordinatorStateResponeDocument;
import hasthi.manager.ManagementRingDocument.ManagementRing;
import hasthi.manager.gui.UIContext;
import hasthi.metamodel.resource.ResourceModelContext;
import hasthi.tools.ManagementRingTools;

public class ResourceModelFactory {
    
    private static hasthi.manager.ManagementRingDocument.ManagementRing ringDocument;
    public static ExternalResourceModel getExternalResourceModel(UIContext uicontext) throws HasthiException{
            try {
                UnicastContianier container = uicontext.getContainer(); 
                //We do not start the container, just use client code
                BaseContext  baseContext = uicontext.getBaseContext();
                
                String coordinationUrl = ManagementRingTools.findCoordinatorFromBootstrapNode(container, baseContext);
                ResourceModelContext modelContext = new ResourceModelContext(coordinationUrl,container,baseContext,null);
                uicontext.setResourceModelContext(modelContext);
                ExternalResourceModel externalResourceModel =  new ExternalResourceModel(modelContext);
                uicontext.setExternalResourceModel(externalResourceModel);
                return externalResourceModel;
            } catch (InterruptedException e) {
                throw new HasthiException(e, FaultCode.LocalError);
            }
    }


  
    
    
    public static ManagementRing getManagerRingState(UIContext uicontext) throws HasthiException{
        String coordinationUrl = uicontext.getCoordinatorUrl();
        UnicastContianier container = uicontext.getContainer(); 
        if(coordinationUrl == null){
            throw new HasthiException("Coordination URL must be defined", FaultCode.InitalizationError);
        }
        //Get Coordinator state document
        CoordinatorStateRequestDocument requestDocument = CoordinatorStateRequestDocument.Factory.newInstance();
        requestDocument.addNewCoordinatorStateRequest();
        MessageContext managementRingRequest = new SimpleMessageContext(requestDocument,coordinationUrl,GET_COORDINATOR_STATE_ACTION);
        ringDocument = ((CoordinatorStateResponeDocument)container.sendReceive(managementRingRequest)).getCoordinatorStateRespone().getManagementRing();
        return ringDocument;
    }

}

